package main

import (
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"tk/mychaincode/supplychain/sdkInit"
	"log"
	"fmt"
	"os"
)

const sdkConfigPath = "/home/tangke/go/src/supplychain/test/ca/config_ca.yaml"

//EnrollUser enroll a user have registerd
func  EnrollUser(sdk *fabsdk.FabricSDK, username string, password string, info *sdkInit.InitInfo) (bool, error) {
	ctx := sdk.Context(fabsdk.WithUser(info.OrgAdmin), fabsdk.WithOrg(info.OrgName))
	mspClient, err := msp.New(ctx)
	if err != nil {
		fmt.Printf("Failed to create msp client: %s\n", err)
		return true, err
	}

	_, err = mspClient.GetSigningIdentity(username)
	if err == msp.ErrUserNotFound {
		fmt.Println("Going to enroll user")
		err = mspClient.Enroll(username, msp.WithSecret(password))
		if err != nil {
			fmt.Printf("Failed to enroll user: %s\n", err)
			return true, err
		}
		fmt.Printf("Success enroll user: %s\n", username)
	} else if err != nil {
		fmt.Printf("Failed to get user: %s\n", err)
		return false, err
	}
	fmt.Printf("User %s already enrolled, skip enrollment.\n", username)
	return true, nil
}

// RegisterlUser Register a new user with username , password and department.
func RegisterlUser(sdk *fabsdk.FabricSDK, username, password, department string, info *sdkInit.InitInfo) error {
	ctx := sdk.Context(fabsdk.WithUser(info.OrgAdmin), fabsdk.WithOrg(info.OrgName))
	mspClient, err := msp.New(ctx)
	if err != nil {
		fmt.Printf("Failed to create msp client: %s\n", err)
	}
	request := &msp.RegistrationRequest{
		Name:        username,
		Type:        "user",
		Affiliation: department,
		Secret:      password,
	}

	secret, err := mspClient.Register(request)
	if err != nil {
		fmt.Printf("register %s [%s]\n", username, err)
		return err
	}
	fmt.Printf("register %s successfully,with password %s\n", username, secret)
	return nil
}

func main(){
	initInfo := &sdkInit.InitInfo{

		ChannelID: "supplychain",
		ChannelConfig: os.Getenv("GOPATH") + "/src/github.com/hyperledger/fabric-samples/first-network/channel-artifacts/channel.tx",

		OrgAdmin:"Admin",
		OrgName:"Org1",
		OrdererOrgName: "orderer.example.com",

		ChaincodeGoPath: os.Getenv("GOPATH"),
		UserName:"User1",
	}

	sdk, err := fabsdk.New(config.FromFile(sdkConfigPath))
	if err != nil{
		log.Fatal("new sdk err:", err)
	}

	//RegisterlUser(sdk, "tangke", "tangke", "org1", initInfo)
	//EnrollUser(sdk, "tangke", "tangke", initInfo)

	EnrollUser(sdk, "admin", "adminpw", initInfo)
	ctx := sdk.Context(fabsdk.WithUser(initInfo.OrgAdmin), fabsdk.WithOrg(initInfo.OrgName))
	mspClient, err := msp.New(ctx)
	if err != nil {
		fmt.Printf("Failed to create msp client: %s\n", err)
		return
	}

	sididentity, err := mspClient.GetSigningIdentity("admin")
	fmt.Println(sididentity)
	
}